package com.graduate.examapp.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.graduate.examapp.entity.HistoryData
import com.graduate.examapp.entity.UserInfoFactory
import com.graduate.examapp.model.HistoryRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Response

class DataViewModel : ViewModel() {
    val historyLiveData = MutableLiveData<List<HistoryData>?>()
    private val historyRepository = HistoryRepository()
    val userHistoryLiveData = MutableLiveData<HistoryData?>()

    fun fetchHistoryData(insName: String) {
        viewModelScope.launch(Dispatchers.IO) {
            val response = historyRepository.fetchHistoryData(insName)
            if (response.code == LoginViewModel.REQUEST_OK) {
                historyLiveData.postValue(response.data)
                val userHistoryData = response.data.find {
                    it.name == (UserInfoFactory.loginData?.username ?: "")
                }
                userHistoryLiveData.postValue(userHistoryData)
            }
        }
    }
}